
// 输入文字最大的个数
const MAX_WORDS_NUM = 500
// 最大上传图片数量
const MAX_IMG_NUM = 6

const db = wx.cloud.database()
// 输入的文字内容
let contentbt = ''
let content = ''
let userInfo = {}
let dianzan = false
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 输入的文字个数
    styleIsolation: 'apply-shared',
    wordsNum: 0,
    footerBottom: 0,
    images: [],
    selectPhoto: true, // 添加图片元素是否显示
    biaoqian:0,
    contentjianche:true,
    contentjianchebt:true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    userInfo = options
    this.getOpenid()
    this.getzhuanti()
  },
  getzhuanti(){
    db.collection('zhuanti').where({
      biao:222
    }).get().then(res => {
      // 查询数据成功 
      this.setData({
        biaoqian1: res.data
      })
    }).catch(err => {
      // 查询数据失败
      console.log(err)
    })
  },
  getOpenid() {
    let that = this;
    wx.cloud.callFunction({
      name: 'getOpenid',
      complete: res => {
        console.log('云函数获取到的openid: ', res.result.openid)
        var openid = res.result.openid;
        that.setData({
          openid: openid
        })
      }
    })
  },
 
  biaoqian: function (e) {
    console.log(e.detail.value)
    this.setData({
      biaoqian: e.detail.value
    })
  },
  onInput(event) {
    // console.log(event.detail.value)
    let wordsNum = event.detail.value.length
    if (wordsNum >= MAX_WORDS_NUM) {
      wordsNum = `最大字数为${MAX_WORDS_NUM}`
    }
    this.setData({
      wordsNum
    })
    content = event.detail.value
    if(content!=''){ 
      wx.cloud.init();
      wx.cloud.callFunction({
        name: 'permissions',
        data: {
          content: content,
        }
      }).then(res => {
        console.log("内容安全审查结果：" + JSON.stringify(res));
        if (res.result.code == "200") { 
          this.setData({
            contentjianche:true
          })
        } else { //执行不通过
          this.setData({
            contentjianche:false
          })
          var v_content = res.result.msg;
          return wx.showModal({
            title: "提示",
            content: v_content,
            showCancel: false,
            confirmText: "确定",
          });
        }
      })}
  },
  onInputbt(event) {
    // console.log(event.detail.value)
    let wordsNum = event.detail.value.length
    if (wordsNum >= 20) {
      wordsNum = `最大字数为${20}`
    }
    contentbt = event.detail.value
    if(contentbt!=''){ 
      wx.cloud.init();
      wx.cloud.callFunction({
        name: 'permissions',
        data: {
          content: contentbt,
        }
      }).then(res => {
        console.log("内容安全审查结果：" + JSON.stringify(res));
        if (res.result.code == "200") { 
          this.setData({
            contentjianchebt:true
          })
        } else { //执行不通过
          this.setData({
            contentjianchebt:false
          })
          var v_content = res.result.msg;
          return wx.showModal({
            title: "提示",
            content: v_content,
            showCancel: false,
            confirmText: "确定",
          });
        }
      })}
  },
  onFocus(event) {
    // 模拟器获取的键盘高度为0
    // console.log(event)
    this.setData({
      footerBottom: event.detail.height,
    })
  },
  onBlur() {
    this.setData({
      footerBottom: 0,
    })
  },

  onChooseImage() {
    // 还能再选几张图片
    let max = MAX_IMG_NUM - this.data.images.length
    wx.chooseImage({
      count: max,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        console.log(res)
        this.setData({
          images: this.data.images.concat(res.tempFilePaths)
        })
        // 还能再选几张图片
        max = MAX_IMG_NUM - this.data.images.length
        this.setData({
          selectPhoto: max <= 0 ? false : true
        })
      },
    })
  },
  onDelImage(event) {
    this.data.images.splice(event.target.dataset.index, 1)
    this.setData({
      images: this.data.images
    })
    if (this.data.images.length == MAX_IMG_NUM - 1) {
      this.setData({
        selectPhoto: true,
      })
    }
  },

  onPreviewImage(event) {
    // 6/9
    wx.previewImage({
      urls: this.data.images,
      current: event.target.dataset.imgsrc,
    })
  },
  send() {
    //1.图片->云存储fileID 云文件ID
    //2.数据库->云数据库
    //数据库：内容、图片fileID、openid、昵称、头像、时间

    //判断content || this.data.images == '' 
    if (contentbt.trim() === '' ||content.trim() === '' || this.data.images == ''||!this.data.contentjianche||!this.data.contentjianchebt) {
      wx.showModal({
        title: '请完善内容',
        content: '',
      })
      return
    }
    wx.showLoading({
      title: '发布中',
      mask: true,
    })
    let promiseArr = []
    let fileIds = []
    //图片上传
    for (let i = 0, len = this.data.images.length; i < len; i++) {
      let p = new Promise((resolve, reject) => {
        let item = this.data.images[i]
        // 文件扩展名
        let suffix = /\.\w+$/.exec(item)[0]
        wx.cloud.uploadFile({
          cloudPath: 'blog/' + Date.now() + '-' + Math.random() * 1000000 + suffix,
          filePath: item,
          success: (res) => {
            console.log(res.fileID)
            fileIds = fileIds.concat(res.fileID)
            resolve()
          },
          fail: (err) => {
            console.error(err)
            reject()
          }
        })
      })
      promiseArr.push(p)
    }
    //存入到云数据库
    Promise.all(promiseArr).then((res) => {
      db.collection('tiezi').add({
        data: {
          ...userInfo,
          contentbt,
          content,
          img: fileIds,
          dianzan,
          id:this.data.biaoqian1[this.data.biaoqian].id,
          biaoqian_ming:this.data.biaoqian1[this.data.biaoqian].content,
          dz:0,
          ip: 300,
          createTime: db.serverDate(),//获取服务端的时间
          biaoqian:parseInt(this.data.biaoqian),   
          opid:this.data.openid
        }
      }).then((res) => {
        wx.hideLoading()
             wx.showToast({
          title: '发布成功',
        }) 
        wx.reLaunch({
          url: "/pages/index/mantie/mantie",
        })
    }).catch((err) => {
      wx.hideLoading()
      wx.showToast({
        title: '发布失败',
      })
    })
  })
  },

/**
 * 生命周期函数--监听页面初次渲染完成
 */
onReady: function () {

},

/**
 * 生命周期函数--监听页面显示
 */
onShow: function () {

},

/**
 * 生命周期函数--监听页面隐藏
 */
onHide: function () {

},

/**
 * 生命周期函数--监听页面卸载
 */
onUnload: function () {

},

/**
 * 页面相关事件处理函数--监听用户下拉动作
 */
onPullDownRefresh: function () {

},

/**
 * 页面上拉触底事件的处理函数
 */
onReachBottom: function () {

},

/**
 * 用户点击右上角分享
 */
onShareAppMessage: function () {

}
})